package com.caigou.modules.personal.ui.board

import android.text.TextUtils
import androidx.activity.viewModels
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseReplyActivity
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.modules.personal.bean.BoardReplyBean
import com.caigou.modules.personal.viewmodel.BoardViewModel
import dagger.hilt.android.AndroidEntryPoint
import java.io.File

/**
 * @author #Suyghur.
 * Created on 2021/12/03
 */
@Route(path = RouterPath.Personal.PAGE_PERSONAL_BOARD_REPLY)
@AndroidEntryPoint
class BoardReplyActivity : BaseReplyActivity() {

    private val boardViewModel: BoardViewModel by viewModels()

    @Autowired(name = AppConstants.USER_ID)
    lateinit var boardUserId: String


    override fun initView() {
        super.initView()
        binding.replyBtnSubmit.setOnClickListener {
            val content = binding.replyEtContent.text.toString()
            val files: MutableList<File> = mutableListOf()
            urls.forEach {
                files.add(File(it))
            }
            boardViewModel.setBoardReply(content, files, AppBackgroundInfo.instance.userBean!!.userId, boardUserId, boardUserId)
        }
    }

    override fun observeViewModel() {
        observe(boardViewModel.boardReplyLiveData, ::handleSetBoardReply)
    }

    private fun handleSetBoardReply(result: Resource<BoardReplyBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("留言失败，请稍后再试")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data == null) {
                    return
                }
                LiveDataBus.get().with(BusKey.REPLY_SUCCESS).value = Any()
                this.finish()
            }
        }
    }
}